package com.example.myapplication;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.example.myapplication.BleGATT.BleGattServer;
import com.example.myapplication.BleGATT.ClientUtils;
import com.example.myapplication.Entity.MessageEntity;
import com.example.myapplication.Entity.SendBoxAdapter;
import com.example.myapplication.databinding.ActivityScanBinding;
import com.example.myapplication.ui.notifications.TalkingFragment;
import com.example.myapplication.ui.notifications.TalkingViewModel;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import java.util.ArrayList;
import java.util.List;

public class RunActivity extends AppCompatActivity
{
    private ClientUtils ClientUtils;
    private boolean isServer=true;
    private List<BluetoothDevice> myBlueDevices;
    private TalkingViewModel viewModel; // 用于保存消息数据

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ClientUtils=new  ClientUtils(getApplicationContext(),this);
        myBlueDevices=new ArrayList<>();
        viewModel = new ViewModelProvider(this).get(TalkingViewModel.class);
        com.example.myapplication.databinding.ActivityScanBinding binding = ActivityScanBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        BottomNavigationView navView = findViewById(R.id.nav_view);
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications).build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(binding.navView, navController);

        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(!bluetoothAdapter.isEnabled()){
            Toast.makeText(this, "蓝牙不可用,请打开蓝牙和定位功能!!!否则无法使用APP功能", Toast.LENGTH_LONG).show();
        }
        //自动启动该服务
        Intent serviceIntent = new Intent(this, BleGattServer.class);
        serviceIntent.putExtra("name", "6666666");
        this.startService(serviceIntent);

    }

    public ClientUtils getClientUtils() {
        return this.ClientUtils;
    }

    public List<BluetoothDevice> getBluetoothDevice(){
        return this.myBlueDevices;

    }
    public void setBluetoothDevice(List<BluetoothDevice> my){
       this.myBlueDevices.addAll(my);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(BleState);
    }

public boolean getisServer(){
        return this.isServer;
}
public void setisServer(boolean state){
         this.isServer=state;
   if(state){
       Log.d("TAG","状态修改为-------服务端！！！！！！！！");
   }
   else {

       Log.d("TAG","状态修改为-------客户端!!!!!!!!!");
   }

    }



    // 在Activity或Fragment的onResume方法中注册广播接收器
    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction("BleStateBroadcast");
        filter.addAction("com.example.ClientToServeData_DATA_UPDATED");
        filter.addAction("com.example.ACTION_DATA_RECEIVED");
        registerReceiver(BleState, filter);
    }
    // 创建广播接收器
    private final BroadcastReceiver BleState = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 处理接收到的广播消息
            if (intent.getAction().equals("BleStateBroadcast")) {
                String message = intent.getStringExtra("message");
                switch (message){
                    case "100":
                        Toast.makeText(context, "蓝牙连接中。。。" + message, Toast.LENGTH_SHORT).show();break;
                    case "200":
                        Toast.makeText(context, "蓝牙连接SERVER成功可以尝试聊天了，如果无法发送请再次点击目标设备连接！！" + message, Toast.LENGTH_SHORT).show();break;
                    case "500":
                        Toast.makeText(context, "断开中 " + message, Toast.LENGTH_SHORT).show();break;
                    case "400":
                        Toast.makeText(context, "蓝牙已断开！！！！ " + message, Toast.LENGTH_SHORT).show();break;
                    case "1000":
                        Toast.makeText(context, "蓝牙连接CLIENT成功可以尝试聊天了！！！！ " + message, Toast.LENGTH_SHORT).show();break;
                }
            }

            if ("com.example.ACTION_DATA_RECEIVED".equals(intent.getAction())) {
                String receivedData = intent.getStringExtra("ReceivedData");
                Log.d("TAG","收到了广播ReceivedData"+receivedData);
                MessageEntity message=new MessageEntity();
                message.setMesssage(receivedData);
                message.setState(true);
                addSendMessage(message);
            }
            //客户端写请求
            if ("com.example.ClientToServeData_DATA_UPDATED".equals(intent.getAction())) {
                String receivedData = intent.getStringExtra("ClientToServeData");
                Log.d("TAG","收到了广播ClientToServeData"+receivedData);
                MessageEntity message=new MessageEntity();
                message.setMesssage(receivedData);
                message.setState(true);
                addSendMessage(message);

            }
        }
    };
    /**
     * @param message 视图更新
     */
    public void addSendMessage(MessageEntity message) {
        viewModel.addMessage(message);
    }
    public TalkingViewModel getViewModel() {
        return viewModel;
    }
}